package com.hw.one.dam2.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.dao.ICityAirDao;
import com.hw.one.dam2.dao.IRegionAirDao;
import com.hw.one.dam2.dao.IRegionSiteDao;
import com.hw.one.dam2.param.CityAirParam;
import com.hw.one.dam2.param.QualityGoalParam;
import com.hw.one.dam2.po.RegionAirQualityPO;
import com.hw.one.dam2.util.CalendarUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 空气质量目标 业务处理层实现类
 * @author 李亚坤
 * @createtime 2017年3月22日10:12:46
 */
@Service
public class ExamineTargetService  implements IExamineTargetService{

    @Autowired
    private IRegionSiteDao regionSiteDao;

    @Autowired
    private ICityAirDao cityAirDao;

    @Autowired
    private IRegionAirDao regionAirDao;

    // 数字保留两位小数
    DecimalFormat decimalformat = new DecimalFormat("#");

    @Override
    public Object findAirQualityTargetGoals(Map paramMap) throws Exception{
        String year = (String) paramMap.get("year");
        String month = (String) paramMap.get("month");
        QualityGoalParam qualityGoalParam = new QualityGoalParam();
        List<String> regionCodeList = new ArrayList<>();
        regionCodeList.add((String) paramMap.get("regionCode"));
        qualityGoalParam.setRegionCodeList(regionCodeList);
        qualityGoalParam.setYear(year);
        qualityGoalParam.setDataType("1");  //查询年度目标
        //查询出 当年所有的目标,然后根据dataType 来判断目标是什么类型的
        List<Map<String, Object>> airQualityYearGoalList = regionSiteDao.findAirQualityGoalByRegionCode(qualityGoalParam);
        //年度
        //优良天数
        JSONObject yFineDays = new JSONObject();
        //PM10
        JSONObject yPM10 = new JSONObject();
        //PM25
        JSONObject yPM25 = new JSONObject();

        //本月
        //优良天数
        JSONObject mFineDays = new JSONObject();
        //PM10
        JSONObject mPM10 = new JSONObject();
        //PM25
        JSONObject mPM25 = new JSONObject();

        yFineDays.put("goal", "-");
        yPM10.put("goal", "-");
        yPM25.put("goal", "-");

        mFineDays.put("goal", "-");
        mPM10.put("goal", "-");
        mPM25.put("goal", "-");
        //遍历空气质量目标
        for(Map yearGoal : airQualityYearGoalList) {
            //年度目标
            if ("1".equals(yearGoal.get("dataType"))) {
                if("FINEDAY".equals(yearGoal.get("goalItem"))) {
                    yFineDays.put("goal", yearGoal.get("itemVal"));
                }
                if ("PM10".equals(yearGoal.get("goalItem"))) {
                    yPM10.put("goal", yearGoal.get("itemVal"));
                }
                if ("PM25".equals(yearGoal.get("goalItem"))) {
                    yPM25.put("goal", yearGoal.get("itemVal"));
                }
            }
            //月份目标
            if ("3".equals(yearGoal.get("dataType")) && month.equals(yearGoal.get("goalTime").toString())) {
                if("FINEDAY".equals(yearGoal.get("goalItem"))) {
                    mFineDays.put("goal", yearGoal.get("itemVal"));
                }
                if ("PM10".equals(yearGoal.get("goalItem"))) {
                    mPM10.put("goal", yearGoal.get("itemVal"));
                }
                if ("PM25".equals(yearGoal.get("goalItem"))) {
                    mPM25.put("goal", yearGoal.get("itemVal"));
                }
            }
        }


        //空气质量数据查询条件
        CityAirParam cityAirParam = new CityAirParam();
        cityAirParam.setStartTime(year + "-01-01");
        cityAirParam.setRegionCodes(regionCodeList);
        cityAirParam.setEndTime(getEndTime(year, month));
        //根据年度时间节点,查询每天的空气质量数据
        List<RegionAirQualityPO> dayYearDataList = regionAirDao.findRegionDayDataByRegionCodesAndTime(cityAirParam);

        //遍历数据,取平均值
        int findDayIndex = 0;
        int PM10Sum = 0;
        int PM25Sum = 0;
        int yearDataSize = 0;
        for (RegionAirQualityPO dayData : dayYearDataList) {
            yearDataSize ++;
            // 100以下是优良
            if (100 >= Integer.valueOf(dayData.getAQI())) {
                findDayIndex ++;
            }
            String PM10Obj = null == dayData.getPM10().getCONCENTRATION() || "".equals(dayData.getPM10().getCONCENTRATION()) ?
                    "0" : dayData.getPM10().getCONCENTRATION();
            PM10Sum = PM10Sum + Integer.valueOf(PM10Obj);

            String PM25Obj = null == dayData.getPM25().getCONCENTRATION() || "".equals(dayData.getPM25().getCONCENTRATION()) ?
                    "0" : dayData.getPM25().getCONCENTRATION();
            PM25Sum = PM25Sum + Integer.valueOf(PM25Obj);
        }
        if (yearDataSize != 0) {
            PM10Sum = PM10Sum/yearDataSize;
            PM25Sum = PM25Sum/yearDataSize;
        }

        yFineDays.put("done", findDayIndex == 0 ? "-" : findDayIndex);
        yPM10.put("done", PM10Sum == 0 ? "-" : PM10Sum);
        yPM25.put("done", PM25Sum == 0 ? "-" : PM25Sum);
        //封装数据
        JSONObject yearGoalData = new JSONObject();
        yearGoalData.put("yFineDays", yFineDays);
        yearGoalData.put("yPM10", yPM10);
        yearGoalData.put("yPM25", yPM25);


        //月份现状
        String m2 = Integer.valueOf(month) > 9 ? month : "0" + month;
        CityAirParam cityAirParamM = new CityAirParam();
        cityAirParamM.setStartTime(year + "-" + m2 + "-01");
        cityAirParamM.setEndTime(year + "-" + m2 + "-31");
        cityAirParamM.setRegionCodes(regionCodeList);
        //根据月份时间节点,查询每天的空气质量数据
        List<RegionAirQualityPO> dayMonthDataList = regionAirDao.findRegionDayDataByRegionCodesAndTime(cityAirParamM);

        int mFindDayIndex = 0;
        int mPM10Sum = 0;
        int mPM25Sum = 0;
        int dataSize = 0;
        for (RegionAirQualityPO dayData : dayMonthDataList) {
            dataSize ++;
            if (100 >= Integer.valueOf(dayData.getPM10().getCONCENTRATION())) {
                mFindDayIndex ++;
            }
            String PM10Obj = null == dayData.getPM10().getCONCENTRATION() || "".equals(dayData.getPM10().getCONCENTRATION()) ?
                    "0" : dayData.getPM10().getCONCENTRATION();
            mPM10Sum = mPM10Sum + Integer.valueOf(PM10Obj);

            String PM25Obj = null == dayData.getPM10().getCONCENTRATION() || "".equals(dayData.getPM10().getCONCENTRATION()) ?
                    "0" : dayData.getPM10().getCONCENTRATION();
            mPM25Sum = mPM25Sum + Integer.valueOf(PM25Obj);
        }
        if (dataSize != 0) {
            mPM10Sum = mPM10Sum/dataSize;
            mPM25Sum = mPM25Sum/dataSize;
        }
        mFineDays.put("done", mFindDayIndex == 0 ? "-" : mFindDayIndex);
        mPM10.put("done", mPM10Sum == 0 ? "-" : mPM10Sum);
        mPM25.put("done", mPM25Sum == 0 ? "-" : mPM25Sum);
        JSONObject monthGoalData = new JSONObject();
        monthGoalData.put("mFineDays", mFineDays);
        monthGoalData.put("mPM10", mPM10);
        monthGoalData.put("mPM25", mPM25);

        JSONObject resultMap = new JSONObject();
        resultMap.put("yearGoalData", yearGoalData);
        resultMap.put("monthGoalData", monthGoalData);
        return resultMap;
    }

    @Override
    public Object findAirQualityGoalCompletionWithArea(Map paramMap) throws Exception{
        String year = (String) paramMap.get("year");
        String month = (String) paramMap.get("month");
        //查询目标条件
        QualityGoalParam qualityGoalParam = new QualityGoalParam();
        List<String> regionCodeList = new ArrayList<>();
        regionCodeList.add((String) paramMap.get("regionCode"));
        qualityGoalParam.setRegionCodeList(regionCodeList);
        qualityGoalParam.setYear(year);
        qualityGoalParam.setMonth(month);
        qualityGoalParam.setDataType("1");  //查询年度目标
        //查询出 当年所有的目标,然后根据dataType 来判断目标是什么类型的
        List<Map<String, Object>> airQualityYearGoalList = regionSiteDao.findAirQualityGoalByRegionCode(qualityGoalParam);
        //时间列表
        JSONArray timeList = new JSONArray();
        List<String> monthList = new ArrayList<>();
        //优良天气目标
        JSONArray fineDayGoal = new JSONArray();

        //PM10目标
        JSONArray PM10DataGoal = new JSONArray();

        //PM25目标
        JSONArray PM25DayGoal = new JSONArray();

        //循环月份
        for (int i = 1; i < 13; i ++) {
            boolean fineDayFlag = false;
            boolean PM10Flag = false;
            boolean PM25Flag = false;
            monthList.add(i+"");
            timeList.add(CalendarUtil.getMonthCnByMonth(i+""));
            for(Map yearGoal : airQualityYearGoalList) {
                if ("3".equals(yearGoal.get("dataType")) && i == Integer.valueOf(yearGoal.get("goalTime").toString())) {
                    if("FINEDAY".equals(yearGoal.get("goalItem"))) {
                        fineDayGoal.add(yearGoal.get("itemVal"));
                        fineDayFlag = true;
                    }
                    if ("PM10".equals(yearGoal.get("goalItem"))) {
                        PM10DataGoal.add(yearGoal.get("itemVal"));
                        PM10Flag = true;
                    }
                    if ("PM25".equals(yearGoal.get("goalItem"))) {
                        PM25DayGoal.add(yearGoal.get("itemVal"));
                        PM25Flag = true;
                    }
                }
            }
            if (!fineDayFlag) {
                fineDayGoal.add("-");
            }
            if (!PM10Flag) {
                PM10DataGoal.add("-");
            }
            if (!PM25Flag) {
                PM25DayGoal.add("-");
            }
        }


        //月份现状
        String m2 = Integer.valueOf(month) > 9 ? month : "0" + month;
        CityAirParam cityAirParam = new CityAirParam();
        cityAirParam.setStartTime(year + "-01-01");
        cityAirParam.setEndTime(year + "-" + m2 + "-31");
        cityAirParam.setRegionCodes(regionCodeList);
        //根据月份时间节点,查询每天的空气质量数据
//        List<Map> dayMonthDataList = cityAirDao.findCityDayDataByRegionCodeAndTime(cityAirParam);
        List<RegionAirQualityPO> dayMonthDataList = regionAirDao.findRegionDayDataByRegionCodesAndTime(cityAirParam);


        //优良天气完成情况
        JSONArray fineDayDone = new JSONArray();
        //PM10完成情况
        JSONArray PM10DataDone = new JSONArray();
        //PM25完成情况
        JSONArray PM25Done = new JSONArray();
        for (String time : monthList) {
            SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.SDF_YM);
            String currTimeStr = year + "-" + (Integer.valueOf(time) > 9 ? time : "0" + time);
            Date currDate = sdf.parse(currTimeStr);
            int mFindDayIndex = 0;
            int mPM10Sum = 0;
            int mPM25Sum = 0;
            int dataSize = 0;
            for (RegionAirQualityPO dayData : dayMonthDataList) {
                Date monitorTime = sdf.parse(dayData.getMONITORTIME());
                if (monitorTime.getTime() == currDate.getTime()) {
                    dataSize ++;
                    if (100 >= Integer.valueOf(dayData.getAQI())) {
                        mFindDayIndex ++;
                    }
                    String PM10Obj = null == dayData.getPM10().getCONCENTRATION() || "".equals(dayData.getPM10().getCONCENTRATION()) ?
                            "0" : dayData.getPM10().getCONCENTRATION();
                    mPM10Sum = mPM10Sum + Integer.valueOf(PM10Obj);

                    String PM25Obj = null == dayData.getPM25().getCONCENTRATION() || "".equals(dayData.getPM25().getCONCENTRATION()) ?
                            "0" : dayData.getPM25().getCONCENTRATION();
                    mPM25Sum = mPM25Sum + Integer.valueOf(PM25Obj);
                }
            }
            if (dataSize != 0) {
                mPM10Sum = mPM10Sum/dataSize;
                mPM25Sum = mPM25Sum/dataSize;
            }
            Date nowTime = sdf.parse(year + "-" + m2);
            if (nowTime.getTime() >= currDate.getTime()) {
                fineDayDone.add(mFindDayIndex == 0 ? "-" : mFindDayIndex);
                PM10DataDone.add(mPM10Sum == 0 ? "-" : mPM10Sum);
                PM25Done.add(mPM25Sum == 0 ? "-" : mPM25Sum);
            }else {
                fineDayDone.add("-");
                PM10DataDone.add("-");
                PM25Done.add("-");
            }

        }
        //优良天气数据
        JSONObject fineDayData = new JSONObject();
        fineDayData.put("fineDayGoal", fineDayGoal);
        fineDayData.put("fineDayDone", fineDayDone);
        //PM10数据
        JSONObject PM10Data = new JSONObject();
        PM10Data.put("PM10Goal", PM10DataGoal);
        PM10Data.put("PM10Done", PM10DataDone);
        //PM25数据
        JSONObject PM25Data = new JSONObject();
        PM25Data.put("PM25Goal", PM25DayGoal);
        PM25Data.put("PM25Done", PM25Done);
        //数据
        JSONObject dataList = new JSONObject();
        dataList.put("fineDayData", fineDayData);
        dataList.put("PM10Data", PM10Data);
        dataList.put("PM25Data", PM25Data);
        //名称
        JSONObject name = new JSONObject();
        name.put("goal", "目标");
        name.put("done", "现状");

        JSONObject resultObj = new JSONObject();
        resultObj.put("dataList", dataList);
        resultObj.put("timeList", timeList);
        resultObj.put("name", name);

        return resultObj;
    }

    @Override
    public Object findAirQualityGoalCompletionWithCity(Map paramMap) {
        String year = (String) paramMap.get("year");
        String month = (String) paramMap.get("month");

        //查询目标条件
        List<String> regionCodeList = new ArrayList<>();
        Map<String, String> regionParamMap = new HashMap<>();
        regionParamMap.put("sortScorpeType", "areaCountySort");
        regionParamMap.put("regionCode", paramMap.get("regionCode").toString());
        List<Map<String,Object>> regionList = regionSiteDao.findRegionListByRegionType(regionParamMap);
        JSONArray areaList = new JSONArray();
        for (Map regionMap : regionList) {
            if ("22".equals(regionMap.get("regionType"))) {
                regionCodeList.add((String) regionMap.get("regionCode"));
                areaList.add(regionMap.get("regionName"));
            }
        }
        QualityGoalParam qualityGoalParam = new QualityGoalParam();
        qualityGoalParam.setRegionCodeList(regionCodeList);
        qualityGoalParam.setYear(year);
        qualityGoalParam.setDataType("1");  //查询年度目标
        List<Map<String, Object>> airQualityYearGoalList = regionSiteDao.findAirQualityGoalByRegionCode(qualityGoalParam);
        //优良天气年度目标
        JSONArray fineDayGoal = new JSONArray();
        //PM10年度目标
        JSONArray PM10Goal = new JSONArray();
        //PM25年度目标
        JSONArray PM25Goal = new JSONArray();


        for (String regionCode : regionCodeList) {
            boolean fineDayFlag = false;
            boolean PM10Flag = false;
            boolean PM25Flag = false;
            for (Map yearGoal : airQualityYearGoalList) {
                if ("1".equals(yearGoal.get("dataType"))) {
                    if (regionCode.equals(yearGoal.get("regionCode"))) {
                        if("FINEDAY".equals(yearGoal.get("goalItem"))) {
                            fineDayGoal.add(yearGoal.get("itemVal"));
                            fineDayFlag = true;
                        }
                        if ("PM10".equals(yearGoal.get("goalItem"))) {
                            PM10Goal.add(yearGoal.get("itemVal"));
                            PM10Flag = true;
                        }
                        if ("PM25".equals(yearGoal.get("goalItem"))) {
                            PM25Goal.add(yearGoal.get("itemVal"));
                            PM25Flag = true;
                        }
                    }
                }
            }
            if (!fineDayFlag) {
                fineDayGoal.add("-");
            }
            if (!PM10Flag) {
                PM10Goal.add("-");
            }
            if (!PM25Flag) {
                PM25Goal.add("-");
            }
        }
        //空气质量数据查询条件
        CityAirParam cityAirParam = new CityAirParam();
        cityAirParam.setStartTime(year + "-01-01");
        cityAirParam.setRegionCodes(regionCodeList);
        cityAirParam.setEndTime(getEndTime(year, month));
        List<RegionAirQualityPO> dayYearDataList = regionAirDao.findRegionDayDataByRegionCodesAndTime(cityAirParam);

        //优良天气完成情况
        JSONArray fineDayDone = new JSONArray();
        //PM10完成情况
        JSONArray PM10Done = new JSONArray();
        //PM25完成情况
        JSONArray PM25Done = new JSONArray();
        for (String regionCode : regionCodeList) {
            int findDayIndex = 0;
            int PM10Sum = 0;
            int PM25Sum = 0;
            int dataSize = 0;
            for (RegionAirQualityPO dayData : dayYearDataList) {
                if (regionCode.equals(dayData.getREGIONCODE())) {
                    dataSize ++;
                    if (100 >= Integer.valueOf(dayData.getAQI())) {
                        findDayIndex ++;
                    }
                    String PM10Obj = null == dayData.getPM10().getCONCENTRATION() || "".equals(dayData.getPM10().getCONCENTRATION()) ?
                            "0" : dayData.getPM10().getCONCENTRATION();
                    PM10Sum = PM10Sum + Integer.valueOf(PM10Obj);

                    String PM25Obj = null == dayData.getPM25().getCONCENTRATION() || "".equals(dayData.getPM25().getCONCENTRATION()) ?
                            "0" : dayData.getPM25().getCONCENTRATION();
                    PM25Sum = PM25Sum + Integer.valueOf(PM25Obj);
                }
            }
            if (dataSize != 0) {
                PM10Sum = PM10Sum/dataSize;
                PM25Sum = PM25Sum/dataSize;
            }
            fineDayDone.add(findDayIndex == 0 ? "-" : findDayIndex);
            PM10Done.add(PM10Sum == 0 ? "-" : PM10Sum);
            PM25Done.add(PM25Sum == 0 ? "-" : PM25Sum);
        }

        JSONObject fineDayData = new JSONObject();
        fineDayData.put("fineDayGoal", fineDayGoal);
        fineDayData.put("fineDayDone", fineDayDone);

        JSONObject PM10Data = new JSONObject();
        PM10Data.put("PM10Goal", PM10Goal);
        PM10Data.put("PM10Done", PM10Done);


        JSONObject PM25Data = new JSONObject();
        PM25Data.put("PM25Goal", PM25Goal);
        PM25Data.put("PM25Done", PM25Done);

        JSONObject dataMap = new JSONObject();
        dataMap.put("fineDayData", fineDayData);
        dataMap.put("PM10Data", PM10Data);
        dataMap.put("PM25Data", PM25Data);

        //名称
        JSONObject name = new JSONObject();
        name.put("goal","目标");
        name.put("done","现状");

        //返回数据
        JSONObject resultMap = new JSONObject();
        resultMap.put("dataList", dataMap);
        resultMap.put("areaList", areaList);
        resultMap.put("name", name);
        return resultMap;
    }

    @Override
    public Map<String, Object> findRegionInfoById(String regionCode) throws Exception {
        return regionSiteDao.findRegionInfoById(regionCode);
    }

    /**
     * 根据年份和 月份 获取结束时间,如果是本月 则是昨天,如果不是则是当月最后一天
     * @param year
     * @param month
     * @return
     */
    private String getEndTime(String year, String month) {
        Calendar now = Calendar.getInstance();
        //判断结束时间
        if (year.equals(now.get(Calendar.YEAR)+"") && month.equals(now.get(Calendar.MONTH) + 1 + "")) {
            //是当前月,取昨天的时间
            Calendar yearCalender = Calendar.getInstance();
            SimpleDateFormat sdf3 = new SimpleDateFormat(DamConstant.SDF_YMD);
            yearCalender.add(Calendar.DATE, -1);
            return sdf3.format(yearCalender.getTime());
        }else {
            //不是当前月,取月份的最后一天,默认认为是31天
            String m = Integer.valueOf(month) > 9 ? month : "0" + month;
            return CalendarUtil.getLastDayOfMonth(year + "-" + m);
        }
    }


}
